package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    ///dish/page?page=1&pageSize=10&name=11
    @GetMapping("/dish/page")
    public ResultInfo findByPage(
            String name,
            @RequestParam(value = "page", defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize){
        Page<Dish> page = dishService.findByPage(name,pageNum,pageSize);
        return ResultInfo.success(page);
    }

    //添加菜品
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish) {
        //因为这个操作同时会影响多个菜品,所以需要将Redis中的所有菜品都删除
        String key = "dish_" + dish.getCategoryId();

        //从redis中删除
        redisTemplate.delete(key);


        dishService.save(dish);
        return ResultInfo.success(null);
    }

    //根据主键查询
    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Dish dish = dishService.findById(id);
        return ResultInfo.success(dish);
    }

    //修改
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish) {

        //因为这个操作同时会影响多个菜品,所以需要将Redis中的所有菜品都删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.update(dish);
        return ResultInfo.success(null);
    }

    //删除
    @DeleteMapping("/dish")
    public ResultInfo delete( Long[] ids) {
        //因为这个操作同时会影响多个菜品,所以需要将Redis中的所有菜品都删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        if (ids != null && ids.length != 0) {
            dishService.deleteByIds(ids);
        }

        return ResultInfo.success(null);
    }

    //停售，启售
    @PostMapping("/dish/status/{status}")
    public ResultInfo stop(@PathVariable("status") Integer status,Long[] ids) {

        //因为这个操作同时会影响多个菜品,所以需要将Redis中的所有菜品都删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        if (ids != null && ids.length != 0) {
            dishService.updateByIds(status,ids);
        }
        return ResultInfo.success(null);
    }

    //根据分类id和status=1查询菜品信息
    @GetMapping("/dish/list")
    public ResultInfo findList(Long categoryId, @RequestParam(defaultValue = "1") Integer status,String name) {
        List<Dish> dishList = dishService.findList(categoryId, status,name);
        return ResultInfo.success(dishList);
    }
}
